package com.snailhd.listener;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.snailhd.cloud.redis.service.RedisService;
import com.snailhd.common.util.web.SpringContextUtil;
import com.snailhd.constant.ListenerEnums;
import com.snailhd.redis.RedisKeys;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 获取注册的监听器
 * @author hd
 * @date 2019-11-23 16:14
 */

@Component
public class ListenerManager {

    public static ExecutorService executor = Executors.newFixedThreadPool(4);

    @Reference
    private RedisService redisService;

    public List<Listener> getListener(ListenerEnums enums){
        List<Listener> listeners = new ArrayList<>();

        List<String> beanNameStrs = redisService.lrange(RedisKeys.CONFIG_LISTENER+enums.name(),0L,-1L);
        for(String beanNameStr:beanNameStrs){
            Listener listener = getListener(beanNameStr,Listener.class);
            if(listener!=null){
                listeners.add(listener);
            }
        }
        return listeners;
    }

    private  <T> T getListener(String beanName, Class<T> listenerClass) {
        T listener = null;
        if (null != listenerClass) {
            try {
                if (StringUtil.isNotBlank(beanName)) {
                    listener = SpringContextUtil.getBean(beanName, listenerClass);
                } else {
                    listener = SpringContextUtil.getBean(listenerClass);
                }
            } catch (BeansException e) {

            }
        }
        return listener;
    }
}
